﻿package e000s {
	import com.greensock.core.SimpleTimeline;
	import flash.display.SimpleButton;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import tools.my_menu;
	import flash.net.URLRequestMethod;
	import flash.net.navigateToURL;
	import com.greensock.TweenLite;
	import com.greensock.easing.*;
	import flash.display.Stage;
	import flash.external.ExternalInterface;
	public class sapload extends MovieClip {
		
		public var msgText:TextField;
		public var browseText:TextField;
		public var upText:TextField;
		public var browseButton:SimpleButton;
		public var upButton:SimpleButton;
		public var proMc:MovieClip;
		
		public var flist:FileReferenceList;
		public var fone:FileReference;
		public var types:String;
		public var ftype:FileFilter;
		
		public var eFormat:TextFormat;
		public var aFormat:TextFormat;
		
		public var upUrl:String;
		public var postArg:URLVariables;
		
		public var uid:uint;
		public var fnumber:uint;
		public var errorCode:uint;
		
		public var maxNum:uint;
		public var maxSize:Number;
		public var tmpArg:String;
		public var fileName:String;
		
		public var ew:Boolean = false;
		public var lw:Boolean = false;
		
		public var oneMod:Boolean = false;
		
		public function sapload():void {
			var mymuen:my_menu = new my_menu();
			mymuen.pushItem("Saplaod v2.1", "http://www.e000s.com/", false);
			mymuen.pushItem("E000S^AS", "http://www.e000s.com/", false);
			mymuen.pushItem("Made In Space.As", "http://www.woria.cn/", false);
			this.contextMenu = mymuen.getMenu();
			browseText = t1;
			upText = t2;
			browseButton = b1;
			upButton = b2;
			proMc = MovieClip(bar);
			msgText = msg;
			
			eFormat = new TextFormat();
			eFormat.color = 0x000000;
			
			aFormat = new TextFormat();
			aFormat.color = 0xcccccccc;
			
			abutton(upButton, upText);
			abutton(browseButton, browseText);
			browseText.mouseEnabled = upText.mouseEnabled = false;
			
			proMc.scaleX = 0;
			
			
			flist = new FileReferenceList();
			flist.addEventListener(Event.SELECT, filerHandler);
			flist.addEventListener(Event.CANCEL, filerHandler);
			
			types = stage.loaderInfo.parameters["types"];
			if (types == null) {
				types = "*.jpg;*.gif;*.png";
			}
			ftype = new FileFilter("授权:[ "+types+" ]", types);
			
			tmpArg = stage.loaderInfo.parameters["args"];
			if (tmpArg == null) {
				tmpArg = "myid=1&yid=2";
			}
			var tmpArray:Array = tmpArg.split(";");
			for (var i:uint; i < tmpArray.length; i++) {
				var t:Array = tmpArray[i].split("=");
				tmpArray[i] = t;
			}
			postArg = new URLVariables();
			for (var k:uint; k < tmpArray.length; k++) {
				postArg[tmpArray[k][0]] = tmpArray[k][1];
			}
			
			browseButton.addEventListener(MouseEvent.CLICK, clickHandler);
			upButton.addEventListener(MouseEvent.CLICK, clickHandler);
			
			//检查上传脚本是否可用
			upUrl = stage.loaderInfo.parameters["upUrl"];
			if (upUrl == null) {
				upUrl = "http://www.sapload.com/upload.php";
			}
			var check:URLLoader = new URLLoader(new URLRequest(upUrl));
			check.addEventListener(HTTPStatusEvent.HTTP_STATUS, checkUrl);
			check.addEventListener(IOErrorEvent.IO_ERROR, checkIoError);
			check.addEventListener(Event.COMPLETE, fireFoxSp);
			
			maxNum = uint(stage.loaderInfo.parameters["maxNum"]);
			maxSize = uint(stage.loaderInfo.parameters["maxSize"]);
			if (maxNum == 0 || maxNum==1) {
				maxNum = 1;
				oneMod = true;
			}
			trace(maxNum + oneMod);
			if (maxSize == 0) {
				maxSize = 8;
			}
			errorCode = 0;
			
			ew = Boolean(uint(stage.loaderInfo.parameters["etmsg"]));
			lw = Boolean(uint(stage.loaderInfo.parameters["ltmsg"]));
			fileName = stage.loaderInfo.parameters["fileName"];
			if (fileName == null) {
				fileName = "Filedata";
			}
		}
		public function fireFoxSp(evnet:Event):void {
			msgText.text = "请择文件先 ^^";
			ebutton(browseButton, browseText);
		}
		public function checkIoError(event:IOErrorEvent):void {
			msgText.text = "无法连接上传脚本！IoError";
		}
		public function checkUrl(event:HTTPStatusEvent):void {
			switch(event.status) {
				case 200:
					errorCode = 0;
				break;
				case 404:
					errorCode = 4;
				break;
			}
		}
		public function abutton(a:SimpleButton, b:TextField):void {
			a.alpha = 0.5;
			a.mouseEnabled = false;
			b.setTextFormat(aFormat);
		}
		public function ebutton(a:SimpleButton, b:TextField):void {
			a.alpha = 1;
			a.mouseEnabled = true;
			b.setTextFormat(eFormat);
		}
		public function clickHandler(event:MouseEvent):void {
			switch(event.target) {
				case browseButton:
					if (oneMod) {
						fone = new FileReference();
						fone.addEventListener(Event.SELECT, filerHandler);
						fone.addEventListener(Event.CANCEL, filerHandler);
						fone.browse(new Array(ftype));
					}else {
						flist.browse(new Array(ftype));
					}
				break;
				case upButton:
					if (oneMod) {
						upOneFile();
					}else {
						uid = 0;
						upFile(uid);
					}
					upText.text = "取消";
					upButton.removeEventListener(MouseEvent.CLICK, clickHandler);
					upButton.addEventListener(MouseEvent.CLICK, stopHandler);
					abutton(browseButton, browseText);
				break;
			}
		}
		public function stopHandler(event:MouseEvent):void {
			msgText.text = "主动取消,请选择需要上传的文件！";
			TweenLite.to(proMc, 1, { ease:Strong.easeOut, scaleX:0 } );
			fone.removeEventListener(ProgressEvent.PROGRESS, proHandler);
			fone.removeEventListener(Event.COMPLETE, comHandler);
			uid = 0;
			resetFileUper();
		}
		public function filerHandler(event:Event):void {
			switch(event.type) {
				case 'select':
					if (oneMod) {
						fnumber = maxNum;
						if (checkFileSize(fone)) {
							msgText.text = fone.name+" 等待上传中……";
							ebutton(upButton, upText);
						}else {
							msgText.text = "未授权操作："+getMsg(errorCode);
						}
					}else {
						fnumber = flist.fileList.length;
						if (checkNum(flist) && checkSize(flist)) {
							msgText.text = "您一共选择 " + event.target.fileList.length + " 个文件";
							ebutton(upButton, upText);
						}else {
							msgText.text = "未授权操作："+getMsg(errorCode);
						}
					}
				break;
				case 'cancel':
					msgText.text = "主动取消,请选择需要上传的文件！";
				break;
				default:
					//trace(event.type);
				break;
			}
		}
		public function checkType(a:FileReferenceList):Boolean {
			var isOk:Boolean = true;
			var l:uint = a.fileList.length;
			for (var i:uint = 0; i < l; i++) {
				var k:Number = types.indexOf(a.fileList[i].type);
				k < 0?isOk = false:isOk = true;
			}
			if (isOk==false) {
				errorCode = 1;
			}
			return isOk;
		}
		public function checkNum(a:FileReferenceList):Boolean {
			var isOk:Boolean = true;
			if (a.fileList.length > maxNum) {
				isOk = false;
			}
			if (isOk==false) {
				errorCode = 2;
			}
			return isOk;
		}
		public function checkSize(a:FileReferenceList):Boolean {
			var isOk:Boolean = true;
			for each (var cks in a.fileList){
				cks.size < 1024 * 1204 * maxSize?isOk = true:isOk = false;
			}
			if (isOk==false) {
				errorCode = 3;
			}
			return isOk;
		}
		public function checkFileSize(a:FileReference):Boolean {
			var isOk:Boolean = true;
			a.size < 1024 * 1204 * maxSize?isOk = true:isOk = false;
			if (isOk==false) {
				errorCode = 3;
			}
			return isOk;
		}
		public function upOneFile():void {
			fone.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			fone.addEventListener(SecurityErrorEvent.SECURITY_ERROR, secHandler);
			fone.addEventListener(ProgressEvent.PROGRESS, proHandler);
			fone.addEventListener(Event.COMPLETE, comHandler);
			
			if (lw) {
				fone.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, showMsgHandler);
			}
			
			var postReq:URLRequest = new URLRequest(upUrl);
			postReq.data = postArg;
			postArg.fileName = new Date().time;
			postReq.method = URLRequestMethod.POST;
			
			fone.upload(postReq, fileName);
		}
		public function upFile(a:uint):void {
			fone = flist.fileList[a];
			fone.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			fone.addEventListener(SecurityErrorEvent.SECURITY_ERROR, secHandler);
			fone.addEventListener(ProgressEvent.PROGRESS, proHandler);
			fone.addEventListener(Event.COMPLETE, comHandler);
			
			if (lw) {
				fone.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, showMsgHandler);
			}
			
			var postReq:URLRequest = new URLRequest(upUrl);
			postReq.data = postArg;
			postArg.fileName = new Date().time;
			postReq.method = URLRequestMethod.POST;
			
			fone.upload(postReq, fileName);
		}
		public function errorHandler(event:IOErrorEvent):void {
			msgText.text = "无法连接上传脚本！- -!";
		}
		public function secHandler(event:SecurityErrorEvent):void {
			msgText.text = "未授权的跨域上传！Orz";
		}
		public function proHandler(event:ProgressEvent):void {
			var trueId:uint = uid + 1;
			proMc.scaleX = event.bytesLoaded / event.bytesTotal;
			if (oneMod) {
				msgText.text = "已上传："+ Math.floor((event.bytesLoaded / event.bytesTotal)*100) + " %";
			}else {
				msgText.text = "正在上传 " + trueId + "/" + fnumber + " 已完成："+ Math.floor((event.bytesLoaded / event.bytesTotal)*100) + " %";
			}
		}
		public function comHandler(event:Event):void {
			if (oneMod) {
				msgText.text = "文件上传完毕！";
				TweenLite.to(proMc, 1, { ease:Strong.easeOut, scaleX:0 } );
				uid = 0;
				resetFileUper();
			}else {
				var trueId:uint = uid + 1;
				msgText.text = "第 " + trueId + " 个文件上传成功";
				if (trueId < fnumber) {
					uid = trueId;
					upFile(uid);
				}else {
					msgText.text = "所有文件上传完毕，共 " + fnumber + " 个";
					TweenLite.to(proMc, 1, { ease:Strong.easeOut, scaleX:0 } );
					uid = 0;
					resetFileUper();
				}
			}
		}
		public function resetFileUper():void {
			upText.text = "上传";
			upButton.removeEventListener(MouseEvent.CLICK, stopHandler);
			upButton.addEventListener(MouseEvent.CLICK, clickHandler);
			if (oneMod) {
				fone = new FileReference();
				fone.addEventListener(Event.SELECT, filerHandler);
				fone.addEventListener(Event.CANCEL, filerHandler);
			}else {
				flist = new FileReferenceList();
				flist.addEventListener(Event.SELECT, filerHandler);
				flist.addEventListener(Event.CANCEL, filerHandler);
			}
			ebutton(browseButton, browseText);
			abutton(upButton, upText);
		}
		public function getMsg(a:uint):String {
			var t:String;
			switch(a) {
				case 0:
					t = "正常状态";
				break;
				case 1:
					t = "未授权的文件类型";
				break;
				case 2:
					t = "超出限定文件个数:"+maxNum;
				break;
				case 3:
					t = "文件大小超出限制:"+maxSize+"M";
				break;
				case 4:
					t = "无法连接上传脚本:404";
				break;
				case 5:
					t = "未知错误！";
				break;
				default:
					t = "未知错误！";
				break;
			}
			return t;
		}
		public function showMsgHandler(event:DataEvent):void {
			if (ew) {
				//trace(event.data);
				ExternalInterface.call("sapLoadMsg", event.data);
			}else {
				if (uid == fnumber) {
					//trace(event.data);
					ExternalInterface.call("sapLoadMsg", event.data);
				}
			}
			
		}
	}
}